import React, {useEffect, useRef} from 'react';
import {Button, Checkbox, Col, Form, Input, message, Row} from 'antd';
import {LockOutlined, UserOutlined} from '@ant-design/icons';
import '../../css/Login/Login.css';
import RequestUtils from "../../utils/RequestUtils";
import Apis from "../../configs/Apis";

/**
 * 登录页
 */
const Login = () => {

    // 提示框
    const [messageApi, contextHolder] = message.useMessage();

    /**
     * 用户登录
     * @param values 输入框的表单信息
     */
    const doLogin = (values) => {
        RequestUtils.post(Apis.userAuthorization.userLogin, {
            userAccount: values.userAccount,
            userPassword: values.userPassword,
            clientType: "pc"
        }).then(res => {
            // 将token保存在cookie中
            RequestUtils.setToken(res.token);
            // 将当前的账号和昵称放到localStorage中
            RequestUtils.setCurrentUserInfo({
                userId: res.userId,
                userNickname: res.userNickname
            });
            messageApi.success('登录成功，即将跳转到管理中心');
            // 稍等片刻跳转到后台首页
            setTimeout(() => {
                window.location.href = '/index';
            }, 1500);
        }).catch(err => {
            messageApi.error(err.message);
        })
    };

    return (
        <div className="login-container">
            {/* 全局提示 */}
            {contextHolder}

            {/* 背景光效 */}
            <div className="light-effect"></div>

            {/* 粒子背景 */}
            <ParticlesBackground/>

            <div className="login-content">
                <div className="login-header">
                    <div className="login-logo">
                        <div className="logo-icon">
                            <UserOutlined/>
                        </div>
                        <h1>运维管理中心登录</h1>
                    </div>
                    <p className="login-desc">请输入账号密码登录系统</p>
                </div>

                <Form
                    name="normal_login"
                    className="login-form"
                    initialValues={{remember: true}}
                    onFinish={doLogin}
                >
                    <Form.Item
                        name="userAccount"
                        rules={[{required: true, message: '请输入账号!'}]}
                    >
                        <Input
                            prefix={<UserOutlined className="site-form-item-icon"/>}
                            placeholder="账号"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item
                        name="userPassword"
                        rules={[{required: true, message: '请输入密码!'}]}
                    >
                        <Input.Password
                            prefix={<LockOutlined className="site-form-item-icon"/>}
                            placeholder="密码"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item>
                        <Form.Item name="remember" valuePropName="checked" noStyle>
                            <Checkbox>记住我</Checkbox>
                        </Form.Item>

                        <a>
                            忘记密码
                        </a>
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="primary"
                            htmlType="submit"
                            className="login-btn"
                            style={{width: '100%'}} // 设置按钮宽度为100%
                        >
                            登录
                        </Button>

                        <div className="login-extra">
                            <Row justify="space-between">
                                <Col>
                                    <a href="">注册账号</a>
                                </Col>
                                <Col>
                                    <a href="">帮助中心</a>
                                </Col>
                            </Row>
                        </div>
                    </Form.Item>
                </Form>
            </div>

            <div className="login-footer">
                © 2025 gengzp 版权所有
            </div>
        </div>
    );
};

export default Login;

/**
 * 粒子背景组件
 */
const ParticlesBackground = () => {
    const canvasRef = useRef(null);
    const particles = useRef([]);
    const animationFrameId = useRef(null);

    useEffect(() => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');

        // 设置Canvas尺寸
        const setCanvasSize = () => {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        };

        setCanvasSize();
        window.addEventListener('resize', setCanvasSize);

        // 创建粒子
        const createParticles = (count = 50) => {
            particles.current = [];
            for (let i = 0; i < count; i++) {
                particles.current.push({
                    x: Math.random() * canvas.width,
                    y: Math.random() * canvas.height,
                    radius: Math.random() * 3 + 1,
                    speedX: (Math.random() - 0.5) * 2,
                    speedY: (Math.random() - 0.5) * 2,
                    color: `rgba(255, 255, 255, ${Math.random() * 0.5 + 0.1})`
                });
            }
        };

        createParticles();

        // 绘制粒子
        const drawParticles = () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            particles.current.forEach(particle => {
                ctx.beginPath();
                ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
                ctx.fillStyle = particle.color;
                ctx.fill();
            });

            // 绘制粒子间的连线
            particles.current.forEach(particle => {
                particles.current.forEach(otherParticle => {
                    const distance = Math.sqrt(
                        Math.pow(particle.x - otherParticle.x, 2) +
                        Math.pow(particle.y - otherParticle.y, 2)
                    );

                    if (distance < 100) {
                        ctx.beginPath();
                        ctx.moveTo(particle.x, particle.y);
                        ctx.lineTo(otherParticle.x, otherParticle.y);
                        ctx.strokeStyle = `rgba(255, 255, 255, ${0.1 - distance / 1000})`;
                        ctx.lineWidth = 0.5;
                        ctx.stroke();
                    }
                });
            });
        };

        // 更新粒子位置
        const updateParticles = () => {
            particles.current.forEach(particle => {
                particle.x += particle.speedX;
                particle.y += particle.speedY;

                if (particle.x < 0 || particle.x > canvas.width) {
                    particle.speedX = -particle.speedX;
                }

                if (particle.y < 0 || particle.y > canvas.height) {
                    particle.speedY = -particle.speedY;
                }
            });

            drawParticles();
            animationFrameId.current = requestAnimationFrame(updateParticles);
        };

        updateParticles();

        // 清理
        return () => {
            cancelAnimationFrame(animationFrameId.current);
            window.removeEventListener('resize', setCanvasSize);
        };
    }, []);

    return <canvas ref={canvasRef} className="particles"/>;
};